package com.jhs.kjs.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.AdminBoardPagingDTO;
import com.jhs.kjs.dto.MenuDTO;
import com.jhs.kjs.model.file.FileDownloadManager;
import com.jhs.kjs.model.file.FileMangerBoard;
import com.jhs.kjs.model.file.FileMangerImage;
import com.jhs.kjs.model.file.IFileManager;
import com.jhs.kjs.service.IAdminBoardService;

@RequestMapping(value = "/admin")
@Controller
public class AdminBoardController extends CommonController {
	private static final Logger logger = LoggerFactory
			.getLogger(AdminBoardController.class);
	@Autowired
	IAdminBoardService adminBoardService;

	@RequestMapping(value = "/adminBoardMain", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView adminBoardMain(
			@ModelAttribute("paging") AdminBoardPagingDTO paging) {
		ModelAndView model = new ModelAndView("admin/board");

		// type = 1 공지사항
		// type = 2 최신판례
		// type = 3 최신법령
		// type = 4 A항목
		// type = 5 B항목
		// type = 6 C항목
		// type = 7 D항목
		// type = 8 E항목
		// type = 9 F항목
		// type = 10 G항목
		// type = 11 H항목

		int menuIndex = paging.getMenuIndex();
		if (menuIndex == 0) {
			paging.setMenuIndex(1);
			menuIndex = 1;
		}
		model.addObject("menuIndex", menuIndex);
		model.addObject("totalPage",
				adminBoardService.getAdminBoardCount(paging));
		model.addObject("menuName", getMenuInfo(menuIndex).getMenuName());
		model.addObject("menuList", getAllUseBoardList());
		return model;
	}

	@RequestMapping(value = "/getAdminBoardList", method = RequestMethod.POST)
	public String getAdminBoardList(HttpServletRequest req, Model model,
			@ModelAttribute("paging") AdminBoardPagingDTO paging) {
		model.addAttribute("boardList",
				adminBoardService.getAdminBoardList(paging));
		model.addAttribute("totalPage",
				adminBoardService.getAdminBoardCount(paging));

		return "";
	}

	@RequestMapping(value = "/adminBoard2Main", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView getAdminBoard2Main(
			@ModelAttribute("paging") AdminBoardPagingDTO paging) {
		ModelAndView model = new ModelAndView("admin/board3");
		// type = 1 공지사항
		// type = 2 최신판례
		// type = 3 최신법령
		// type = 4 EBS 정보
		// type = 5 A항목
		// type = 6 B항목
		// type = 7 C항목
		// type = 8 D항목
		// type = 9 E항목
		// type = 10 F항목
		// type = 11 G항목
		// type = 12 H항목
		int menuIndex = paging.getMenuIndex();
		if (menuIndex == 0) {
			paging.setBoardType(5);
			menuIndex = 5;
		}
		model.addObject("menuIndex", menuIndex);
		model.addObject("totalPage",
				adminBoardService.getAdminBoardCount(paging));
		model.addObject("menuName", getMenuInfo(menuIndex).getMenuName());
		model.addObject("menuList", getAllUseBoardList());
		return model;
	}

	@RequestMapping(value = "/getAdminBoard2List", method = RequestMethod.POST)
	public String getAdminBoard2List(HttpServletRequest req, Model model,
			@ModelAttribute("paging") AdminBoardPagingDTO paging) {
		model.addAttribute("boardList",
				adminBoardService.getAdminBoardList(paging));
		model.addAttribute("totalPage",
				adminBoardService.getAdminBoardCount(paging));

		return "";
	}
	
	@RequestMapping(value = "/adminBoardWrite", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView adminBoardWrite(HttpServletRequest req, @ModelAttribute("paging") AdminBoardPagingDTO paging){
		ModelAndView model = new ModelAndView();

		int menuIndex = paging.getMenuIndex();
		MenuDTO menu = getMenuInfo(menuIndex);

		if (menu.getMenuType() == 0) {
			model.setViewName("admin/write");
		} else {
			model.setViewName("admin/board3_write");
		}

		String mode = paging.getMode();

		Map<String, Long> param = new HashMap<String, Long>();
		param.put("menuIndex",
				Long.parseLong(String.valueOf(paging.getMenuIndex())));
		param.put("textID", paging.getTextID());

		AdminBoardPagingDTO dto = null;

		String contents;
		if ("modify".equals(mode)) {
			dto = adminBoardService.getAdminBoardView(param);
			contents = dto.getContents();
			// contents = contents.replaceAll("<br>", "\n");
			dto.setContents(contents);
			model.addObject("boardView", dto);
			model.addObject("provider", adminBoardService.getProvider(param));
		}

		model.addObject("mode", mode);
		model.addObject("msg", "");
		model.addObject("menu", menu);
		model.addObject("menuList", getAllBoardList());
		return model;
	}

	@RequestMapping(value = "/adminRegistBoard", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView adminRegistBoard(HttpServletRequest req,
			AdminBoardPagingDTO param) throws Exception {

		ModelAndView mvc = new ModelAndView();

		String orgName = "";
		IFileManager fileMng = new FileMangerImage(req);

		MultipartFile imgAttachmentFile = param.getImgAttachmentFile();
		if (imgAttachmentFile != null) {
			fileMng.setFile(param.getImgAttachmentFile());
			if (fileMng.saveFile()) {
				param.setImgAttachmentPath(fileMng.getFileName());
				param.setImgAttachment(fileMng.getOriginalFilename());
			}
		}
		fileMng = new FileMangerBoard(req);
		MultipartFile attachmentFile = param.getAttachmentFile();
		if (attachmentFile != null) {
			fileMng.setFile(param.getAttachmentFile());
			if (fileMng.saveFile()) {
				param.setAttachmentPath(fileMng.getFileName());
				param.setAttachment(fileMng.getOriginalFilename());
			}
		}
		String contents = param.getContents();
		// contents = contents.replaceAll("\n", "<br>");
		// contents = contents.replaceAll("'", "＇");

		param.setContents(contents);
		String mode = param.getMode();
		long textID = 0;
		if ("insert".equals(mode)) {
			textID = adminBoardService.getBoardSeq();
			param.setTextID(Long.parseLong(String.valueOf(textID)));

			adminBoardService.registBoard(param);
			mvc.addObject("msg", "등록되었습니다.");
		} else if ("modify".equals(mode)) {
			textID = param.getTextID();
			Map<String, Long> proMap = new HashMap<String, Long>();
			proMap.put("textID", textID);

			adminBoardService.deleteProvider(proMap); // 정보제공자 삭제
			adminBoardService.updateBoard(param);
			mvc.addObject("msg", "수정되었습니다.");
		}

		int menuIndex = param.getMenuIndex();
		MenuDTO menu = getMenuInfo(menuIndex);
		int menuType = menu.getMenuType();
		if (menuType == 1) {
			// 정보제공자 등록
			List<Map<String, String>> providerList = new ArrayList<Map<String, String>>();
			Map<String, String> providerParam = new HashMap<String, String>();
			List<String> providerName = param.getProviderName();
			List<String> providerAddr = param.getProviderAddress();

			int listSize = providerName.size();
			String name = "";
			for (int i = 0; i < listSize; i++) {
				name = providerName.get(i);

				if (!"".equals(name)) {
					providerParam = new HashMap<String, String>();
					providerParam.put("textID", String.valueOf(textID));
					providerParam.put("morder", (i + 1) + "");
					providerParam.put("name", providerName.get(i));
					providerParam.put("addr", providerAddr.get(i));
					providerList.add(providerParam);
				}
			}

			Map<String, Object> myBatisParam = new HashMap<String, Object>();
			myBatisParam.put("data", providerList);

			if (providerList.size() > 0) {
				adminBoardService.insertProviderInfo(myBatisParam);
			}
			mvc.setViewName("admin/board3_write");
		} else {
			mvc.setViewName("admin/write");
		}
		mvc.addObject("menu", menu);

		return mvc;
	}

	@RequestMapping(value = "/adminBoardView", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView adminBoardView(HttpServletRequest req,
			AdminBoardPagingDTO boardDTO) throws Exception {
		Map<String, Long> param = new HashMap<String, Long>();
		param.put("menuIndex",
				Long.parseLong(String.valueOf(boardDTO.getMenuIndex())));
		param.put("textID",
				Long.parseLong(String.valueOf(boardDTO.getTextID())));

		ModelAndView mvc = new ModelAndView();
		String view = "";

		Long menuIndex = param.get("menuIndex");
		MenuDTO menu = getMenuInfo(menuIndex.intValue());
		int menuType = menu.getMenuType();
		if (menuType == 0) {
			view = "admin/view";
		} else {
			view = "admin/board_view";
		}
		AdminBoardPagingDTO dto = adminBoardService.getAdminBoardView(param);
		String content = dto.getContents();

		// content = content.replaceAll("&lt;", "<");
		// content = content.replaceAll("&gt;", ">");
		dto.setContents(content);
		mvc.addObject("boardView", dto);
		mvc.addObject("textID", boardDTO.getTextID());
		mvc.addObject("provider", adminBoardService.getProvider(param)); // 정보제공자
		mvc.addObject("menu", menu);
		mvc.addObject("menuList", getAllUseBoardList());
		// mvc.addObject("nextBoardView",
		// adminBoardService.getNextBoardView(param));
		// mvc.addObject("prevBoardView",
		// adminBoardService.getPrevBoardView(param));
		mvc.setViewName(view);
		return mvc;
	}

	@RequestMapping(value = "/hasFile", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String hasFile(HttpServletRequest req, Model model,
			@RequestParam Map<String, String> param) throws Exception {
		Long textID = Long.parseLong(param.get("textID"));
		Map<String, Long> param1 = new HashMap<String, Long>();
		param1.put("textID", textID);
		String fileName = param.get("fileName");
		IFileManager fileMng = new FileMangerBoard(req);

		String path = "";
		String originalFileName = param.get("originalFileName");
		if (fileMng.loadFile(fileName, originalFileName)) {
			path = fileMng.getDownloadFilePath() + originalFileName;
		}

		File file = new File(path);
		model.addAttribute("exists", file.exists());

		return "";
	}

	@RequestMapping(value = "/download", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView download(HttpServletRequest req,
			@RequestParam Map<String, String> param) throws Exception {
		String fileName = param.get("fileName");
		IFileManager fileMng = new FileMangerBoard(req);

		String path = "";
		String originalFileName = param.get("originalFileName");
		if (fileMng.loadFile(fileName, originalFileName)) {
			path = fileMng.getDownloadFilePath() + originalFileName;
			logger.debug(path);
		}

		File file = new File(path);
		return new ModelAndView("fileDownloadView", "downloadFile", file);
	}

	@RequestMapping(value = "/deleteAdminBoard", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String deleteAdminBoard(HttpServletRequest request, Model model,
			@RequestParam Map<String, Long> param) throws IOException {
		String msg = "";
		try {
			adminBoardService.deleteBoard(param);
			adminBoardService.deleteProvider(param); // 정보제공자 삭제
			msg = "삭제 되었습니다.";
		} catch (Exception e) {
			e.printStackTrace();
			msg = "오류가 발생했습니다.";
		}

		model.addAttribute("msg", msg);
		return "";
	}

	@RequestMapping(value = "/write2", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String write2(HttpServletRequest req, Model model,
			@RequestParam Map<String, String> param) throws Exception {

		return "admin/write2";
	}

	@RequestMapping(value = "/board/imgUploader", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String imgUploader(HttpServletRequest request, Model model,
			AdminBoardPagingDTO param) throws Exception {
		IFileManager fileMng = new FileMangerImage(request);

		MultipartFile update_image = param.getUpdate_image();

		if (update_image != null) {
			fileMng.setFile(update_image);
			if (fileMng.saveFile()) {
				model.addAttribute("filePath", fileMng.getFileName());
			}
		}
		return "admin/file_uploader";
	}

	
	@RequestMapping(value = "/writeSample", method = RequestMethod.GET)
	public ModelAndView writeSample(HttpServletRequest req, @ModelAttribute("paging") AdminBoardPagingDTO paging){
		ModelAndView model = new ModelAndView();
		
		model.setViewName("admin/writeSample");		
		
		return model;
	}
}
